package com.stedu.security;

import cn.hutool.core.util.StrUtil;
import com.stedu.exception.CaptchaException;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {
    private final String loginUrl = "/login";
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //判断是否是post的登录请求，如果是就要验证验证码是否正确
        //获取请求路径
        String url = request.getRequestURI();
        //获取请求方式
        String method = request.getMethod();


        //验证验证码是否正确
        if(loginUrl.equals(url) && method.equalsIgnoreCase("POST")) {
            //获取登录请求中携带的验证码Id
            String captchaId = request.getParameter("captchaId");
            //获取用户输入的验证码
            String captchaInput = request.getParameter("captchaInput");

            //获取Redis中的验证码文本
            String captchaRedis = (String)redisUtil.get(captchaId);

            //判断验证码是否正确
            try {
                validate(captchaId, captchaInput, captchaRedis);
            }catch (CaptchaException e){
                loginFailureHandler.onAuthenticationFailure(request, response, e);
            }

        }
        //放行
        filterChain.doFilter(request, response);
    }

    //判断验证码是否正确
    public void validate(String captchaId, String captchaInput, String captchaRedis) {
        if(StrUtil.isBlank(captchaId) || StrUtil.isBlank(captchaInput)) {
            throw new CaptchaException("验证码Id或验证码输入为空");
        }
        if(!captchaRedis.equalsIgnoreCase(captchaInput)) {
            throw new CaptchaException("验证码不存在");
        }
    }
}